/**
 *
 *
 *
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.oss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.dao.SysOssDao;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("sysOssService")
public class SysOssServiceImpl extends ServiceImpl<SysOssDao, SysOssEntity> implements SysOssService {

	private final Logger logger = LoggerFactory.getLogger(SysOssServiceImpl.class);

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String fileName = (String) params.get("fileName");
		IPage<SysOssEntity> page = this.page(
			new Query<SysOssEntity>().getPage(params),
			new QueryWrapper<SysOssEntity>()
				.like(StringUtils.isNotBlank(fileName),"original_file_name", fileName)
		);

		return new PageUtils(page);
	}

	public String upload(MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		//上传文件
		String originalFilename = file.getOriginalFilename();
		logger.info("上传文件名称：{}", originalFilename);
		String url = OSSFactory.build().uploadSuffix(file.getBytes(), originalFilename);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setOriginalFileName(originalFilename);
		ossEntity.setCreateDate(new Date());
		this.save(ossEntity);
		return url;
	}

	@Override
	public String download(HttpServletRequest request, HttpServletResponse response, File outFile, String outFileName) throws Exception {
		logger.info("下载文件：{}", outFile.getAbsolutePath());
		if (!outFile.exists()) {
			return null;
		}
		String userAgent = request.getHeader("User-Agent");
		String downLoadFileName = outFileName;
		if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
			downLoadFileName = java.net.URLEncoder.encode(downLoadFileName, "UTF-8");
		} else {// 非IE浏览器的处理：
			downLoadFileName = new String(downLoadFileName.getBytes("UTF-8"), "ISO-8859-1");
		}
		// 开始下载
		response.setContentType("application/octet-stream");
		response.setHeader("content-type", "application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;fileName=" + downLoadFileName);// 设置文件名
		byte[] buffer = new byte[1024];
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			fis = new FileInputStream(outFile);
			bis = new BufferedInputStream(fis);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
			logger.info("文件下载完毕：{}", outFile.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
